package cn.nxcoder.blog.service.impl;

import cn.nxcoder.blog.core.AbstractService;
import cn.nxcoder.blog.dao.CommentMapper;
import cn.nxcoder.blog.entity.Comment;
import cn.nxcoder.blog.service.CommentService;
import com.vdurmont.emoji.EmojiParser;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 博客Service
 *
 * @author shengwu ni
 * @date 2018/05/09 22:38
 */
@Service
public class CommentServiceImpl extends AbstractService<Comment> implements CommentService {

    @Resource
    private CommentMapper commentMapper;

    @Override
    public List<Comment> listCommentByBlogId(Long blogId) {

        // 获取所有最顶层级的评论
        List<Comment> firstComments = commentMapper.findByBlogIdAndParentId(blogId, 0L);
        if (firstComments == null || firstComments.size() == 0) {
            return firstComments;
        }
            
        for (Comment comment : firstComments) {
            // 先把comment内容中的emoji表情还原
            String s = EmojiParser.parseToUnicode(comment.getContent());
            comment.setContent(s);

            List<Comment> childrenList = commentMapper.findByBlogIdAndParentId(blogId, comment.getId());
            if (childrenList != null && childrenList.size() > 0) {
                for (Comment reply : childrenList) {
                    reply.setParentComment(comment);
                    loop(reply, blogId);
                }
                comment.setReplyComment(tempList);
                tempList = new ArrayList<>();
            }
        }

        // 将所有顶级节点以及所有子节点都返回
        return firstComments;

    }

    @Override
    public Integer saveComment(Comment comment) {
        Long parentCommentId = comment.getParentComment().getId();
        if (parentCommentId != -1) {
            comment.setParentid(parentCommentId);
        } else {
            comment.setParentid(0L);
        }
        comment.setCreateTime(new Date());
        return commentMapper.insert(comment);
    }

    /**
     * 循环获取每个顶点的评论节点
     * @param comment
     * @return
     */
    private void loop(Comment comment, Long blogId) {

        // 先将emoji表情还原
        String s = EmojiParser.parseToUnicode(comment.getContent());
        comment.setContent(s);

        tempList.add(comment);

        List<Comment> childrenList = commentMapper.findByBlogIdAndParentId(blogId, comment.getId());
        if (childrenList != null && childrenList.size() > 0) {
            for (Comment reply : childrenList) {
                reply.setParentComment(comment);
                loop(reply, blogId);
            }
        }
    }

    private List<Comment> tempList = new ArrayList<>();

}
